import tkinter as tk
from tkinter import scrolledtext, messagebox, simpledialog, Listbox, Toplevel
import subprocess
import threading
import os
import datetime


class DeviceLogFrame:
    def __init__(self, master, device_id):
        self.device_id = device_id
        self.frame = tk.Frame(master)
        self.frame.pack(pady=5)

        self.label = tk.Label(self.frame, text=device_id)
        self.label.pack()

        self.log_text = scrolledtext.ScrolledText(self.frame, width=80, height=10)
        self.log_text.pack(pady=5)

        self.start_button = tk.Button(self.frame, text="Start", command=self.start_logging)
        self.start_button.pack(side=tk.LEFT, padx=5)

        self.stop_button = tk.Button(self.frame, text="Stop", command=self.stop_logging)
        self.stop_button.pack(side=tk.LEFT, padx=5)

        self.process = None
        self.log_file = None

    def start_logging(self):
        self.log_text.delete(1.0, tk.END)  # 清空日志框
        subprocess.run(f"adb -s {self.device_id} logcat -c", shell=True)  # 清空日志缓存

        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        self.log_file = os.path.join(os.getcwd(), f"{self.device_id}_{timestamp}.log")
        command = f"adb -s {self.device_id} logcat -v threadtime"
        self.process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        thread = threading.Thread(target=self.collect_logs)
        thread.start()

    def stop_logging(self):
        if self.process:
            self.process.terminate()
            self.process = None

    def collect_logs(self):
        with open(self.log_file, 'a') as f:
            while True:
                output = self.process.stdout.readline()
                if output:
                    formatted_output = f"[{self.device_id}] {output.decode()}"
                    self.log_text.insert(tk.END, formatted_output)
                    self.log_text.see(tk.END)
                    f.write(formatted_output)  # 同步写入文件
                else:
                    break


class LogCollectorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("车载安卓日志收集器")
        self.root.geometry("800x600")  # 设置初始窗口大小

        self.device_frames = []
        self.device_list = self.get_adb_devices()

        self.add_device_button = tk.Button(root, text="Add Device", command=self.open_device_selection)
        self.add_device_button.pack(pady=10)

    def get_adb_devices(self):
        try:
            output = subprocess.check_output("adb devices", shell=True).decode()
            devices = []
            for line in output.splitlines()[1:]:
                if line.strip() and "\tdevice" in line:
                    devices.append(line.split()[0])
            return devices
        except Exception as e:
            messagebox.showerror("Error", f"Failed to get ADB devices: {e}")
            return []

    def open_device_selection(self):
        if not self.device_list:
            messagebox.showwarning("No Devices", "No devices found. Make sure your devices are connected.")
            return

        selection_window = Toplevel(self.root)
        selection_window.title("Select Device")

        listbox = Listbox(selection_window)
        for device in self.device_list:
            listbox.insert(tk.END, device)
        listbox.pack(pady=10)

        select_button = tk.Button(selection_window, text="Select",
                                  command=lambda: self.add_device(listbox.get(tk.ACTIVE), selection_window))
        select_button.pack(pady=5)

    def add_device(self, device_id, window):
        if device_id:
            device_log_frame = DeviceLogFrame(self.root, device_id)
            self.device_frames.append(device_log_frame)
            window.destroy()
        else:
            messagebox.showwarning("No Device Selected", "Please select a device from the list.")


if __name__ == "__main__":
    root = tk.Tk()
    app = LogCollectorApp(root)
    root.mainloop()
